package com.lightsh.list;
import java.util.List;

import com.lightsh.reflect.ReflectHelper;
import com.lightsh.utility.Constants;

import android.content.Context;
import android.util.Log;
import android.util.MonthDisplayHelper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public class CommonListAdapter extends BaseAdapter {
	private Class<? extends AbstractListItemView> mConvertClass;
	private Context mContext;
	private List<? extends AbstractListItem> mItemDatas;
	private OnItemSelectListener mItemSelectListener;
	
	/**
	 * 
	 * @param context
	 * @param items
	 * @param convertClass 必须要有以一个{@link Context}作为作为参数的构造函数的类
	 */
	public CommonListAdapter(Context context, List<? extends AbstractListItem> items, Class<? extends AbstractListItemView> convertClass){
		mContext = context;
		mItemDatas = items;
		mConvertClass = convertClass;
	}
	
	/**
	 * 
	 * @param context
	 * @param items
	 * @param convertClass 必须要有以一个{@link Context}和{@link OnItemSelectListener}作为作为参数的构造函数的类
	 * @param listener		item被点击时的回调
	 */
	public CommonListAdapter(Context context, List<? extends AbstractListItem> items, Class<? extends AbstractListItemView> convertClass, OnItemSelectListener listener){
		this(context, items, convertClass);
		// FIXME 这里的listener需要增加一个过渡，该adapter应该处理view的item的选中状态转换?
		mItemSelectListener = listener;
	}
	
	public int getCount() {
		return mItemDatas.size();
	}

	public Object getItem(int position) {
		return mItemDatas.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		if (mItemDatas == null) {
			return null;
		}
		if (convertView == null) {
			AbstractListItemView itemView = null;
			try {
				if(mItemSelectListener != null){
					itemView = (AbstractListItemView)ReflectHelper.reflectConstructor(mConvertClass, new Class<?>[]{Context.class, OnItemSelectListener.class}, new Object[]{mContext, mItemSelectListener});
				}else{
					itemView = (AbstractListItemView)ReflectHelper.reflectConstructor(mConvertClass, new Class<?>[]{Context.class}, new Object[]{mContext});
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			itemView.updateView(mItemDatas.get(position), position);
			convertView = itemView;
		} else {
			((AbstractListItemView) convertView).updateView(mItemDatas.get(position), position);
		}
		return convertView;
	}

}
